package letterCombinations17;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LetterCombinations {

    public static void main(String[] args) {
        LetterCombinations letterCombinations = new LetterCombinations();
        letterCombinations.letterCombinationsR("234");
    }


    public List<String> letterCombinationsR(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
        return combinations;
    }

    /**
     * @param combinations 返回结果容器
     * @param phoneMap 数字字母对应关系
     * @param digits 传入参数
     * @param index 遍历到第几个字符和遍历深度
     * @param combination 临时拼接字符串
     */
    public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
            if (index == digits.length()) {
                //递归停止条件 数字长度就是递归深度，所以当index深度与数字长度相同就是最后一层递归
                combinations.add(combination.toString());
            } else {
                char digit = digits.charAt(index);//此时获取'2'
                String letters = phoneMap.get(digit);//abc
                int lettersCount = letters.length();
                for (int i = 0; i < lettersCount; i++) {
                    combination.append(letters.charAt(i));
                    backtrack(combinations, phoneMap, digits, index + 1, combination);

                    combination.deleteCharAt(index);
                }
            }
    }

}
